import entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Collectors收集器测试用例
 * @author dayu
 * @create 2023-09-09 14:39
 */
@RunWith(JUnit4.class)
public class CollectorsDemo {
    private static List<User> users=new ArrayList<>();

    static {
        users.add(new User("祖宇",18,new BigDecimal(7000)));
        users.add(new User("王峰",20,new BigDecimal(8000)));
        users.add(new User("斌哥",30,new BigDecimal(10000)));
        users.add(new User("玉成",20,new BigDecimal(9000)));
    }

    /**
     * counting 用来统计集合总数
     */
    @Test
        public void Test01(){
        Long collect = users.stream().collect(Collectors.counting());
        System.out.println(collect);
        }

    /**
     * maxBy 求拥有最大值的对象 minBy求拥有最小值的对象
     */
    @Test
    public void Test02(){
        Optional<User> optionalUser = users.stream().collect(Collectors.maxBy(Comparator.comparing(User::getBablane)));
        System.out.println(optionalUser.get());
        optionalUser = users.stream().collect(Collectors.minBy(Comparator.comparing(User::getAge)));
        System.out.println(optionalUser.get());
    }

    /**
     * summingInt 进行数据汇总
     */
    @Test
    public void Test03(){
        Integer collect  = users.stream().collect(Collectors.summingInt(User::getAge));
        System.out.println(collect);
        int sum = users.stream().mapToInt(User::getAge).sum();
        System.out.println(sum);
    }

    /**
     * averagingLnt 进行数据取平均数
     */
    @Test
    public void Test04(){
        Double collect  = users.stream().collect(Collectors.averagingInt(User::getAge));
        System.out.println(collect);
    }

    /**
     * joining 对数据进行拼接
     */
    @Test
    public void Test05(){
        String collect = users.stream().map(User::getUsername).collect(Collectors.joining(","));
        System.out.println(collect);
    }

    /**
     * groupingBy 对数据进行分组 结果集合为Map k为指定的字段 v为List集合类型为一开始的类型
     */
    @Test
    public void Test06(){
        Map<String, List<User>> collect = users.stream().collect(Collectors.groupingBy(User::getUsername));
        System.out.println(collect);
    }

}
